import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/components/UserItem.dart';

// 推荐用户
class ReferUsers extends StatefulWidget {
  const ReferUsers({super.key});

  @override
  State<ReferUsers> createState() => _ReferUsersState();
}

class _ReferUsersState extends State<ReferUsers>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  List<dynamic> _list = [];
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    getData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void getData() async {
    var res = await Api.imRecommendUser();
    if (res['code'] == 1) {
      // 更新数据
      setState(() {
        _list = res['data']['lists'] ?? [];
      });
    }
  }

  // 模拟数据刷新
  Future<void> _refreshData() async {
    try {
      getData();
    } catch (e) {
      TDToast.showIconText('失败',
          icon: TDIcons.error,
          direction: IconTextDirection.vertical,
          context: context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshableListView(
      onRefresh: _refreshData,
      children: [
        ..._list.map((item) => Column(
              children: [UserItem(user: item), const SizedBox(height: 10)],
            )),
        Padding(
          padding: const EdgeInsets.fromLTRB(100, 20, 100, 20),
          child: TextButton(
            onPressed: getData,
            style: TextButton.styleFrom(
              minimumSize: const Size(200, 50),
              backgroundColor: Colors.blue,
            ),
            child: const Text('换一批'),
          ),
        )
      ],
      // children: [],
    );
  }
}
